package com.sunday.android.fangdaifu.bukong.fragment.tab;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.squareup.picasso.Picasso;
import com.sunday.android.fangdaifu.bukong.BaseApp;
import com.sunday.android.fangdaifu.bukong.R;
import com.sunday.android.fangdaifu.bukong.activity.SettingActivity;
import com.sunday.android.fangdaifu.bukong.activity.login.ForgetPwdActivity;
import com.sunday.android.fangdaifu.bukong.activity.login.LoginActivity;
import com.sunday.android.fangdaifu.bukong.entity.Member;
import com.sunday.android.fangdaifu.bukong.entity.UploadImgBack;
import com.sunday.android.fangdaifu.bukong.http.ApiClient;
import com.sunday.android.fangdaifu.bukong.utils.BaseUtil;
import com.sunday.android.fangdaifu.bukong.utils.Constants;
import com.sunday.android.fangdaifu.bukong.utils.LazyFragment;
import com.sunday.common.event.EventBus;
import com.sunday.common.imageselector.MultiImageSelectorActivity;
import com.sunday.common.model.ResultDO;
import com.sunday.common.utils.DeviceUtils;
import com.sunday.common.utils.ImageUtils;
import com.sunday.common.utils.ToastUtils;
import com.sunday.common.widgets.CircleImageView;
import com.sunday.common.widgets.UIAlertView;
import com.sunday.member.base.BaseFragment;
import com.sunday.member.common.MemberConst;
import com.sunday.member.utils.SharePerferenceUtils;
import com.sunday.member.utils.UploadUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by yun_sheng on 2017/6/29.
 */

public class MyFragment extends BaseFragment {
    @Bind(R.id.avator)
    CircleImageView avator;
    @Bind(R.id.tv_phone)
    TextView tvPhone;
    @Bind(R.id.ly_update_pwd)
    RelativeLayout lyUpdatePwd;
    @Bind(R.id.ly_setting)
    RelativeLayout lySetting;
    @Bind(R.id.btn_exit_login)
    TextView btnExitLogin;
    private Member member;
    private int w;

    public static MyFragment newInstance() {
        MyFragment fragment = new MyFragment();
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_my, container, false);
        ButterKnife.bind(this, rootView);
        return rootView;
    }


    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        w = DeviceUtils.getDisplay(mContext).widthPixels;
        member = new Gson().fromJson(SharePerferenceUtils.getIns(mContext).getOAuth() , Member.class);
        initView();
    }

    private void initView(){
        if (!TextUtils.isEmpty(member.getLogo())){
            Picasso.with(mContext).
                    load(member.getLogo()).
                    centerCrop().
                    resize(160,  160).
                    placeholder(R.drawable.default_error).into(avator);
        }
        tvPhone.setText(member.getName());
    }

    @OnClick({R.id.ly_update_pwd, R.id.ly_setting, R.id.btn_exit_login,R.id.avator})
    void onClick(View v) {
        switch (v.getId()) {
            case R.id.ly_update_pwd:
                Bundle bundle = new Bundle();
                bundle.putString("title","修改密码");
                BaseUtil.openActivity(mContext, ForgetPwdActivity.class,bundle);
                break;
            case R.id.ly_setting:
                BaseUtil.openActivity(mContext, SettingActivity.class);
                break;
            case R.id.btn_exit_login:
                showLogoutDialog();
                break;
            case R.id.avator:
                toImage();
                break;
        }
    }

    public void toImage() {
        intent = new Intent(mContext, MultiImageSelectorActivity.class);
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_COUNT, 1);
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_MODE, MultiImageSelectorActivity.MODE_SINGLE);
        startActivityForResult(intent, Constants.REQUEST_IMG_CODE);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode==Constants.REQUEST_IMG_CODE){
            String selectImg = ImageUtils.getCompressImagePath(data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT).get(0));
            Picasso.with(mContext)
                    .load(new File(selectImg))
                    .placeholder(R.drawable.default_error)
                    .error(R.drawable.default_error)
                    .resize(w / 5, w / 5)
                    .centerInside()
                    .into(avator);
            uploadImg(UploadUtils.getRequestBody(selectImg));
        }
    }

    private void uploadImg(final RequestBody requestBody) {
        showLoadingDialog(0);
        Call<ResultDO<UploadImgBack>> call
                = ApiClient.getApiAdapter().AaImage(requestBody);
        call.enqueue(new Callback<ResultDO<UploadImgBack>>() {
            @Override
            public void onResponse(Call<ResultDO<UploadImgBack>> call, Response<ResultDO<UploadImgBack>> response) {
                dissMissDialog();
                if (response.body() == null || isFinish) {
                    return;
                }
                if (response.body() != null && response.body().getCode() == 0) {
                    update(response.body().getResult().getUrl());
                } else {
                    ToastUtils.showToast(mContext, response.body().getMessage());
                }
            }

            @Override
            public void onFailure(Call<ResultDO<UploadImgBack>> call, Throwable t) {
                dissMissDialog();
                ToastUtils.showToast(mContext, "网络错误");
            }
        });
    }

    private void update(String logo) {
        showLoadingDialog(0);
        Call<ResultDO> call
                = ApiClient.getApiAdapter().AsUploadLogo(member.getId(),logo);
        call.enqueue(new Callback<ResultDO>() {
            @Override
            public void onResponse(Call<ResultDO> call, Response<ResultDO> response) {
                dissMissDialog();
                if (response.body() == null || isFinish) {
                    return;
                }
                if (response.body() != null && response.body().getCode() == 0) {
                    ToastUtils.showToast(mContext, "头像修改成功");
                } else {
                    ToastUtils.showToast(mContext, response.body().getMessage());
                }
            }

            @Override
            public void onFailure(Call<ResultDO> call, Throwable t) {
                dissMissDialog();
                ToastUtils.showToast(mContext, "网络错误");
            }
        });
    }


    private void showLogoutDialog(){
        BaseUtil.showDialog(mContext, "退出登录？", new BaseUtil.BaseUtilClickListener() {
            @Override
            public void doRightbtn() {
                SharePerferenceUtils.getIns(mContext).removeKey(Constants.AUTH);
                SharePerferenceUtils.getIns(mContext).removeKey(MemberConst.MEMBER_ID);
                SharePerferenceUtils.getIns(mContext).removeKey(Constants.IS_LOGIN);
                SharePerferenceUtils.getIns(mContext).removeKey(Constants.IS_FIRST);
                BaseUtil.openActivity(mContext, LoginActivity.class);
                getActivity().finish();
            }
        });
    }
}
